// pages/login/login.js
var api = require('../../api/api');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: "/images/toux.png",
    nick_name: "",
    mobile: '',
    userInfo: {
      nickname: "",
      avatar: ""
    },
    type: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.type) {
      this.setData({
        type: options.type
      })
      wx.setNavigationBarTitle({
        title: '用户信息',
      })
    }
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      console.log(userInfo)
      this.setData({
        avatarUrl: userInfo.avatar,
        nick_name: userInfo.nickname,
        mobile: userInfo.mobile
      })
    }

  },
  login() {
    if (!this.data.avatarUrl) {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      })
      return false;
    }
    if (!this.data.nick_name) {
      wx.showToast({
        title: '请填写昵称',
        icon: 'none'
      })
      return false;
    }
    if (!this.data.mobile) {
      wx.showToast({
        title: '请授权手机号',
        icon: 'none'
      })
      return false;
    }
    let data = {
      nickname: this.data.nick_name,
      avatar: this.data.avatarUrl,
      mobile: this.data.mobile
    }
    if (!this.data.type) { //登录
      api.post('/oauth/saveInfo', data).then(res => {
        wx.setStorageSync('userInfo', res.userInfo);
        wx.showToast({
          title: '登录成功',
          icon:'none',
          success:function(){
             setTimeout(function(){
              wx.navigateBack({
                delta: 1,
              })
             },1000)
          }
        })
      })
    }else{ //更新
      api.post('/oauth/saveInfo', data).then(res => {
        wx.setStorageSync('userInfo', res.userInfo);
          wx.showToast({
            title: '更新成功',
            icon:'none',
            success:function(){
               setTimeout(function(){
                wx.navigateBack({
                  delta: 1,
                })
               },1000)
            }
          })
          
      })
    }

  },
  wxLogin(){
    let that = this;
    let token = wx.getStorageSync('token')
    if(token){
      that.login();
    }else{
      wx.login({
        success: res => {
          api.post('/oauth/wechatLogin' ,{
            code:res.code
          }).then(res => {
            wx.setStorageSync('token', res.token);
            wx.setStorageSync('userInfo', res.userInfo);
            that.login();
          })
        }
      })
    }
  },
  //获取手机号
  getMobile(e) {
    console.log(e);
    console.log('手机', e.detail.code);
    api.post('/oauth/mobile', {
      code: e.detail.code
    }).then(phoneRes => {
      this.setData({
        mobile: phoneRes.mobile
      })
    })
  },
  //上传图片
  get_upload_image(path) {
    let that = this;
    wx.showLoading({
      title: '上传中...',
    })
    // api.post('/common/upload',{
    //   file:path
    // }).then(res=>{

    // })
    wx.uploadFile({
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'Authorization': wx.getStorageSync('token')
      },
      filePath: path,
      name: 'file',
      url: api.httpUrl + "/common/upload",
      success: res => {
        wx.hideLoading({
          success: (res) => {},
        })
        let upload_data = res.data;
        upload_data = JSON.parse(upload_data)
        const upload_tx = upload_data.data.path;
        this.data.upload_tx = upload_tx;
        const upload_image = upload_data.data.url;
        console.log("upload_image", upload_image)
        let userInfo = this.data.userInfo;
        userInfo.avatar = upload_tx;
        this.setData({
          avatarUrl: upload_image
        })
        console.log(upload_data)
      }
    })

  },
  click_login() {
    wx.getUserProfile({
      desc: 'desc',
      success: res => {
        console.log(res)
      }
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    console.log("头像", e)
    this.get_upload_image(avatarUrl) //上传头像

    // this.setData({
    //   avatarUrl,
    // })
  },
  user_login(userInfo) {
    wx.login({
      success: res => {
        var code = res.code;
        const login = app.ul.login;
        const method = 'POST';
        const params = {
          code,
          userInfo
        }

        app.requestData(login, method, params).then(res => {
          console.log("登录", res)
          if (res.status) {
            wx.showToast({
              title: res.data.message,
            })
            const token = res.data.token;
            const user_info = res.data.userInfo;
            wx.setStorageSync('token', token)
            wx.setStorageSync('userInfo', user_info)
            setTimeout(res => {
              wx.switchTab({
                url: '../my/my',
              })
            }, 800)
          }
        })
      }
    })

  },
  //输入昵称
  input_name(e) {
    const value = e.detail.value;
    this.data.nick_name = value;
  },
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let userInfo = this.data.userInfo;
    userInfo.nickname = e.detail.value.inputName;
    this.data.userInfo = userInfo;
    console.log("userInfo", userInfo)
    if (!userInfo.avatar) {
      wx.showToast({
        title: '请先上传头像',
        icon: "none"
      })
    } else if (!userInfo.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: "none"
      })
    } else {
      //提交登录信息
      this.user_login(userInfo)
    }
  },
  formReset(e) {
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: ''
    })
  },
  submit() {
    console.log("点击登录")
  },
  //

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})